package com.xjrsoft.module.customer.erp_model.eRP_StockTransferStock.service.impl;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.dbmodel.utils.DataSourceUtil;
import com.xjrsoft.core.tool.utils.StringUtil;
import com.xjrsoft.module.customer.erp_model.eRP_StockTransferStock.dto.ErpStocktransferstockentryDto;
import com.xjrsoft.module.customer.erp_model.eRP_StockTransferStock.entity.ErpStocktransferstock;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xjrsoft.module.customer.erp_model.eRP_StockTransferStock.entity.ErpStocktransferstockentry;
import com.xjrsoft.module.customer.erp_model.eRP_StockTransferStock.mapper.ErpStocktransferstockentryMapper;
import com.xjrsoft.module.customer.erp_model.eRP_StockTransferStock.dto.ErpStocktransferstockListDto;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;

import java.math.BigDecimal;
import java.util.List;
import com.xjrsoft.module.customer.erp_model.eRP_StockTransferStock.mapper.ErpStocktransferstockMapper;
import com.xjrsoft.module.customer.erp_model.eRP_StockTransferStock.service.IErpStocktransferstockService;
import com.xjrsoft.core.mp.base.BaseService;
import com.xjrsoft.module.customer.erp_model.eRP_StockTransferStock.vo.ErpStocktransferstockentryVo;
import com.xjrsoft.module.customer.erp_model.erp_inventoryManage.entity.ErpInventory;
import com.xjrsoft.module.customer.erp_model.erp_inventoryManage.service.IErpInventoryService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.experimental.Helper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import sun.invoke.empty.Empty;

/**
 *  服务实现类
 *
 * @author pp
 * @since 2021-10-08
 */
@Service
@AllArgsConstructor
public class ErpStocktransferstockServiceImpl extends BaseService<ErpStocktransferstockMapper, ErpStocktransferstock> implements IErpStocktransferstockService {

	private ErpStocktransferstockentryMapper erpStocktransferstockentryMapper;
	@Autowired
	private IErpInventoryService erpInventoryService;

	@Override
	public IPage<ErpStocktransferstock> getPageList(ErpStocktransferstockListDto pageListDto) {
		Wrapper<ErpStocktransferstock> wrapper = Wrappers.<ErpStocktransferstock>query().lambda()				.eq(!StringUtil.isEmpty(pageListDto.getF_TransferCode()), ErpStocktransferstock::getFTransfercode, pageListDto.getF_TransferCode())
				.ge(!StringUtil.isEmpty(pageListDto.getF_TransferDate_Start()), ErpStocktransferstock::getFTransferdate, pageListDto.getF_TransferDate_Start())
				.le(!StringUtil.isEmpty(pageListDto.getF_TransferDate_End()), ErpStocktransferstock::getFTransferdate, pageListDto.getF_TransferDate_End());
		return this.page(ConventPage.getPage(pageListDto), wrapper);
	}

	@Override
	public String addErpStocktransferstock(ErpStocktransferstock erpStocktransferstock,List<ErpStocktransferstockentryDto> erpStocktransferstockentryDtos, List<ErpStocktransferstockentry> erpStocktransferstockentryList) {
		if(updateInfo(erpStocktransferstockentryDtos)!=null)
		{
			return "库存数量小于调拨数量";
		}
		else
		{
			String erpStocktransferstockId = IdWorker.get32UUID();
			erpStocktransferstock.setFId(erpStocktransferstockId);
			erpStocktransferstockentryList.forEach(erpStocktransferstockentry -> erpStocktransferstockentry.setFTransferstockid(erpStocktransferstockId));
			this.saveBatch(erpStocktransferstockentryList, ErpStocktransferstockentry.class, ErpStocktransferstockentryMapper.class);
			boolean isSuccess = this.save(erpStocktransferstock);
			return isSuccess ? erpStocktransferstockId : null;
		}
	}

	@SneakyThrows
	public String updateInfo(List<ErpStocktransferstockentryDto> erpStocktransferstockentryDtos)
	{
		boolean isNoQua=false;
			//判断库存是否足够
			for (int i=0;i<erpStocktransferstockentryDtos.size();i++)
			{
				String sql1="select * from erp_inventory i where i.F_WareHouseId='"+erpStocktransferstockentryDtos.get(i).getFOutstockwearid()+"'and i.F_GoodsId='"+erpStocktransferstockentryDtos.get(i).getFGoodsid()+"'";
				List<Entity> inventoryList= Db.use(DataSourceUtil.getDataSource("localDB")).query(sql1);
				if(inventoryList.size()>0) {
					if (erpStocktransferstockentryDtos.get(i).getFUnitid().equals(erpStocktransferstockentryDtos.get(i).getFBasicunit())) {
						BigDecimal amount = inventoryList.get(0).getBigDecimal("F_BasicAmount");
						if (erpStocktransferstockentryDtos.get(i).getFQuantity().compareTo(amount) == 1) {
							isNoQua = true;
						}
					} else if (erpStocktransferstockentryDtos.get(i).getFUnitid().equals(erpStocktransferstockentryDtos.get(i).getFComunit())) {
						BigDecimal amount = inventoryList.get(0).getBigDecimal("F_ComAmount");
						if (erpStocktransferstockentryDtos.get(i).getFQuantity().compareTo(amount) > 0) {
							isNoQua = true;
						}
					} else {
						BigDecimal converTate = null;
							//查询转换率
						BigDecimal baseConverRate = null;
						//显示单位转换率
						BigDecimal comConverRate=null;
							String sql2 = "select c.F_Id,c.F_ConvertRate,c.F_FullName,c.F_ConvertId,c.F_Description from erp_unitconvertchild c left join erp_unitconvert u on u.F_Id=c.F_ConvertId where c.F_ConvertId='" + erpStocktransferstockentryDtos.get(i).getFUnitid() + "'";
							List<Entity> list = Db.use(DataSourceUtil.getDataSource("localDB")).query(sql2);
							for (int j = 0; j < list.size(); j++) {
								if (list.get(j).get("f_fullname").toString().equals(erpStocktransferstockentryDtos.get(i).getFComunit().toString()))
								{
									comConverRate=new BigDecimal(list.get(j).get("F_ConvertRate").toString());
								}
								if (list.get(j).get("f_fullname").toString().equals(erpStocktransferstockentryDtos.get(i).getFBasicunit().toString()))
								{
									baseConverRate=new BigDecimal(list.get(j).get("F_ConvertRate").toString());
								}
							}
						BigDecimal amount1 = inventoryList.get(0).getBigDecimal("F_BasicAmount");
						BigDecimal amount2 = inventoryList.get(0).getBigDecimal("F_ComAmount");
						if (erpStocktransferstockentryDtos.get(i).getFQuantity().multiply(baseConverRate).compareTo(amount1) >0 || erpStocktransferstockentryDtos.get(i).getFQuantity().multiply(comConverRate).compareTo(amount2) >0) {
							isNoQua = true;
						}
					}
				}
				else {
					isNoQua=true;
				}
			}
			if(isNoQua)
			{
				return "库存数量小于调拨数量";
			}
			//修改库存
			for (int i=0;i<erpStocktransferstockentryDtos.size();i++)
			{
				BigDecimal Qua=erpStocktransferstockentryDtos.get(i).getFQuantity();
				//根据商品id和仓库id查询是否有此商品的库存数据
				String sql1="SELECT * FROM erp_inventory i where i.F_WarehouseId='"+erpStocktransferstockentryDtos.get(i).getFInstockwearid()+ "' and i.F_GoodsId='"+erpStocktransferstockentryDtos.get(i).getFGoodsid()+"'";
				List<Entity> isInventory1= Db.use(DataSourceUtil.getDataSource("localDB")).query(sql1);
				ErpInventory erpInventory1=new ErpInventory();
				//根据商品id和仓库id查询是否有此商品的库存数据
				String sql2="SELECT * FROM erp_inventory i where i.F_WarehouseId='"+erpStocktransferstockentryDtos.get(i).getFOutstockwearid()+ "' and i.F_GoodsId='"+erpStocktransferstockentryDtos.get(i).getFGoodsid()+"'";
				List<Entity> isInventory2= Db.use(DataSourceUtil.getDataSource("localDB")).query(sql2);
				ErpInventory erpInventory2=new ErpInventory();
				BigDecimal aftBasicQua1= isInventory2.get(0).getBigDecimal("f_basicamount");
				BigDecimal aftComamQua1=isInventory2.get(0).getBigDecimal("f_comamount");
				//查询转换率
				String sql="select c.F_Id,c.F_ConvertRate,c.F_FullName,c.F_ConvertId,c.F_Description from erp_unitconvertchild c left join erp_unitconvert u on u.F_Id=c.F_ConvertId where c.F_ConvertId='"+erpStocktransferstockentryDtos.get(i).getFUnitid()+"'";
				List<Entity>  list= Db.use(DataSourceUtil.getDataSource("localDB")).query(sql);
				BigDecimal baseConverRate = null;
				//显示单位转换率
				BigDecimal comConverRate=null;
				for (int j=0;j<list.size();j++)
				{
					if (list.get(j).get("f_fullname").toString().equals(erpStocktransferstockentryDtos.get(i).getFComunit().toString()))
					{
						comConverRate=new BigDecimal(list.get(j).get("F_ConvertRate").toString());
					}
					if (list.get(j).get("f_fullname").toString().equals(erpStocktransferstockentryDtos.get(i).getFBasicunit().toString()))
					{
						baseConverRate=new BigDecimal(list.get(j).get("F_ConvertRate").toString());
					}
				}
				erpInventory2.setFId(isInventory2.get(0).get("f_id").toString());//根据id修改 一定呀加这句
				erpInventory2.setFBasicamount(aftBasicQua1.subtract(Qua));
				erpInventory2.setFComamount(aftComamQua1.subtract(Qua));
				if (!erpStocktransferstockentryDtos.get(i).getFComunit().equals(erpStocktransferstockentryDtos.get(i).getFUnitid()))
				{
					erpInventory2.setFComamount(aftBasicQua1.subtract(Qua.multiply(comConverRate)));
				}
				if (!erpStocktransferstockentryDtos.get(i).getFBasicunit().equals(erpStocktransferstockentryDtos.get(i).getFUnitid()))
				{
					erpInventory2.setFBasicamount(aftBasicQua1.subtract(Qua.multiply(baseConverRate)));
				}
				erpInventoryService.updateById(erpInventory2);
				erpInventory1.setFGoodsid(erpStocktransferstockentryDtos.get(i).getFGoodsid());
				erpInventory1.setFWarehouseid(erpStocktransferstockentryDtos.get(i).getFInstockwearid());
				if(isInventory1.size()>0)
				{
					BigDecimal aftBasicQua= isInventory1.get(0).getBigDecimal("f_basicamount");
					BigDecimal aftComamQua=isInventory1.get(0).getBigDecimal("f_comamount");
					erpInventory1.setFId(isInventory1.get(0).get("f_id").toString());//根据id修改 一定呀加这句
					erpInventory1.setFBasicamount(aftBasicQua.add(Qua));
					erpInventory1.setFComamount(aftComamQua.add(Qua));
					if(!erpStocktransferstockentryDtos.get(i).getFBasicunit().equals(erpStocktransferstockentryDtos.get(i).getFUnitid())&&!erpStocktransferstockentryDtos.get(i).getFComunit().equals(erpStocktransferstockentryDtos.get(i).getFUnitid()))
					{
						erpInventory1.setFBasicamount(aftBasicQua.add(Qua.multiply(baseConverRate)));
						erpInventory1.setFComamount(aftComamQua.add(Qua.multiply(comConverRate)));
					}
					if (!erpStocktransferstockentryDtos.get(i).getFComunit().equals(erpStocktransferstockentryDtos.get(i).getFUnitid()))
					{
						erpInventory1.setFComamount(aftComamQua.add(Qua.multiply(comConverRate)));
					}
					if (!erpStocktransferstockentryDtos.get(i).getFBasicunit().equals(erpStocktransferstockentryDtos.get(i).getFUnitid()))
					{
						erpInventory1.setFBasicamount(aftBasicQua.add(Qua.multiply(baseConverRate)));
					}
					erpInventoryService.updateById(erpInventory1);
				}
				else
				{
					erpInventory1.setFBasicamount(Qua);
					erpInventory1.setFComamount(Qua);
					if(!erpStocktransferstockentryDtos.get(i).getFBasicunit().equals(erpStocktransferstockentryDtos.get(i).getFUnitid())&&!erpStocktransferstockentryDtos.get(i).getFComunit().equals(erpStocktransferstockentryDtos.get(i).getFUnitid()))
					{
						erpInventory1.setFBasicamount(Qua.multiply(baseConverRate));
						erpInventory1.setFComamount(Qua.multiply(comConverRate));
					}
					if (!erpStocktransferstockentryDtos.get(i).getFComunit().equals(erpStocktransferstockentryDtos.get(i).getFUnitid()))
					{
						erpInventory1.setFComamount(Qua.multiply(comConverRate));
					}
					if (!erpStocktransferstockentryDtos.get(i).getFBasicunit().equals(erpStocktransferstockentryDtos.get(i).getFUnitid()))
					{
						erpInventory1.setFBasicamount(Qua.multiply(baseConverRate));
					}
					erpInventoryService.addErpInventory(erpInventory1);
				}
			}
           return null;
	}

	@Override
	public boolean updateErpStocktransferstock(String id, ErpStocktransferstock erpStocktransferstock, List<ErpStocktransferstockentry> erpStocktransferstockentryList) {
//		erpStocktransferstock.setFId(id);
//		erpStocktransferstockentryList.forEach(erpStocktransferstockentry -> erpStocktransferstockentry.setFTransferstockid(id));
//		erpStocktransferstockentryMapper.delete(Wrappers.<ErpStocktransferstockentry>query().lambda().eq(ErpStocktransferstockentry::getFTransferstockid, id));
//		this.saveBatch(erpStocktransferstockentryList, ErpStocktransferstockentry.class, ErpStocktransferstockentryMapper.class);
		return this.updateById(erpStocktransferstock);
	}

	public List<ErpStocktransferstockentry> getErpStocktransferstockentryByParentId(String parentId){
		Wrapper wrapper = Wrappers.<ErpStocktransferstockentry>query().lambda().eq(ErpStocktransferstockentry::getFTransferstockid, parentId);
		return erpStocktransferstockentryMapper.selectList(wrapper);
	}

	public List<ErpStocktransferstockentryVo> getInfo(String F_TransferStockId){
		return erpStocktransferstockentryMapper.getInfo(F_TransferStockId);
	}
}
